//
//  BSKClassifyManageViewController.m
//  MicroMemory
//
//  Created by rimi on 16/7/15.
//  Copyright © 2016年 BlueSky. All rights reserved.
//


#import <AVOSCloud/AVOSCloud.h>

#import "BSKClassifyManageViewController.h"
#import "UIView+SDAutoLayout.h"
#import "BSKTheme.h"
#import "BSKconsts.h"
#import "BSKClassifyTableViewCell.h"
#import "BSKClassifySettingViewController.h"
#import "BSKDBManager.h"
#import "BSKNoteType.h"
#import "BSKNote.h"
#import "AFNetworking.h"
#import "BSKTypePasswdAlertView.h"
#import "UIViewController+BSKToast.h"

@interface BSKClassifyManageViewController () <UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) UIView *navView;
@property (strong, nonatomic) UIButton *backButton;
@property (strong, nonatomic) UIButton *addButton;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UITableView *classifyTableView;
@property (strong, nonatomic) NSMutableArray *dataSource;
@property(nonatomic,strong) BSKDBManager * magager;//数据库管理对象
@end

@implementation BSKClassifyManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.9525 green:0.9525 blue:0.9525 alpha:1.0];
    _magager = [[BSKDBManager alloc]init];
    [self initializeUserInterface];
    [self initializeDataSource];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(typeListDataBaseDidChange:) name:BSKtypeListChangeNotification object:nil];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BSKtypeListChangeNotification object:nil];
}
- (void)initializeDataSource {
    
    [_magager openDataBase:@"notedatabase.db"];
    NSString * userId = @"null";
    if([AVUser currentUser]){
        userId = [AVUser currentUser].objectId;
    }
    FMResultSet * resultSet = [_magager queryDataFromTable:@"type" Columnns:@[@"*"] condition:[NSString stringWithFormat:@"userID = '%@' ORDER BY typeID",userId]];
    
    NSMutableArray * types = [NSMutableArray array];
    while ([resultSet next]) {
        BSKNoteType *aNoteType = [BSKNoteType typeWithResultSet:resultSet];
        if (![aNoteType.pictureFileName isEqualToString:@"null"]) {
            [types addObject:[BSKNoteType typeWithResultSet:resultSet]];
        }
    }
    [resultSet close];
    [_magager.fmDatabase close];
    self.dataSource = [NSMutableArray arrayWithArray:types];
    [self.classifyTableView reloadData];
}
- (void)initializeUserInterface {
    self.navView = [[UIView alloc] init];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.titleLabel = [[UILabel alloc] init];
    self.classifyTableView = [[UITableView alloc] init];
    
    [self.view addSubview:self.navView];
    [self.navView addSubview:self.backButton];
    [self.navView addSubview:self.titleLabel];
    [self.navView addSubview:self.addButton];
    
    [self.view addSubview:self.classifyTableView];
    
    self.navView.sd_layout.topEqualToView(self.view)
    .widthRatioToView(self.view, 1)
    .heightIs(StatusBarHeight + NavigationBarHeight);
    self.navView.backgroundColor = [BSKTheme curentTheme].themeColor;
    
    self.backButton.sd_layout.topSpaceToView(self.navView, StatusBarHeight + 5)
    .leftSpaceToView(self.navView, 5)
    .widthIs(NavigationBarHeight - 10)
    .heightIs(NavigationBarHeight - 10);
    self.backButton.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
    [self.backButton setImage:[UIImage imageNamed:@"back" ] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.titleLabel.sd_layout.centerXIs(self.view.centerX)
    .centerYEqualToView(self.backButton);
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:25];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = @"分类管理";
    [self.titleLabel sizeToFit];
    
    self.addButton.sd_layout.topSpaceToView(self.navView, StatusBarHeight + 5)
    .rightSpaceToView(self.navView, 10)
    .widthIs(NavigationBarHeight - 10)
    .heightIs(NavigationBarHeight - 10);
    self.addButton.imageEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    [self.addButton setImage:[UIImage imageNamed:@"add(1)" ] forState:UIControlStateNormal];
    [self.addButton addTarget:self action:@selector(addButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.classifyTableView.sd_layout.topSpaceToView(self.navView, 0)
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomEqualToView(self.view);
    self.classifyTableView.backgroundColor = [UIColor clearColor];
    self.classifyTableView.bounces = NO;
    self.classifyTableView.showsVerticalScrollIndicator = NO;
    self.classifyTableView.delegate = self;
    self.classifyTableView.dataSource = self;
}
#pragma mark - 自定义方法
-(void)typeListDataBaseDidChange:(NSNotification *)notify{
    [self initializeDataSource];
}
- (void)backButtonAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)addButtonAction:(UIButton *)sender {
    BSKClassifySettingViewController *addClassifyManageVC = [[BSKClassifySettingViewController alloc] init];
    addClassifyManageVC.status = YES;
    [self.navigationController pushViewController:addClassifyManageVC animated:YES];
}
- (void)deleteAType:(BSKNoteType *)type {
    
    NSString * userId = @"null";
    if([AVUser currentUser]){
        userId = [AVUser currentUser].objectId;
    }
    // 删除和该分类相关的日记文件，更新相关的日记数据使其文件属性为“null”
    [_magager openDataBase:@"notedatabase.db"];
    FMResultSet * resultSet = [_magager queryDataFromTable:@"note" Columnns:@[@"*"] condition:[NSString stringWithFormat:@"typeID = '%@' and userID = '%@'",type.typeID, userId]];
    NSMutableArray * willDeleteNotes = [NSMutableArray array];
    while ([resultSet next]) {
        BSKNote *note = [BSKNote noteWithResultSet:resultSet];
        [willDeleteNotes addObject:note];
    }
    [resultSet close];
    [_magager.fmDatabase close];
    
    for(BSKNote * deleteNote in willDeleteNotes) {
        NSString * noteDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *fileName = deleteNote.noteFileName;
        NSError *error = [[NSError alloc] init];
        [fileManager removeItemAtPath:[NSString stringWithFormat:@"%@/%@",noteDirPath,fileName] error:&error];
        [_magager updateDataToTable:@"note" Columnns:@[@[@"noteFileName", @"null"]] condition:[NSString stringWithFormat:@"noteID = '%@' and userID = '%@'", deleteNote.noteID, userId]];
    }
    
    // 删除文件对应的图片（两种情况）
    if (![[type.pictureFileName substringToIndex:12] isEqualToString:@"localHost://"]) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *fileName = type.pictureFileName;
        NSError *error = [[NSError alloc] init];
        [fileManager removeItemAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, fileName] error:&error];
    }
    [_magager updateDataToTable:@"type" Columnns:@[@[@"pictureFileName", @"null"]] condition:[NSString stringWithFormat:@"typeID = '%@' and userID = '%@'", type.typeID, userId]];
    [[NSNotificationCenter defaultCenter]postNotificationName:BSKtypeListChangeNotification object:nil];
    [self initializeDataSource];
}
- (void)presentAlertWithMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *classifyCellIdentifier = @"classifyTableViewCell";
    BSKClassifyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:classifyCellIdentifier];
    if (!cell) {
        cell = [[BSKClassifyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:classifyCellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    BSKNoteType * type = self.dataSource[indexPath.row];
    if (type.secretMode) {
        cell.keyImageView.hidden = NO;
    } else {
        cell.keyImageView.hidden = YES;
    }
    cell.titleLabel.text = type.typeName;
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    BSKNoteType *type = self.dataSource[indexPath.row];
    if (type.secretMode) {
        BSKTypePasswdAlertView * alertView = [[BSKTypePasswdAlertView alloc]initWithNoteType:type successCallBack:^(BOOL isSuccess) {
            if(isSuccess){
                BSKClassifySettingViewController *classifySettingVC = [[BSKClassifySettingViewController alloc] init];
                classifySettingVC.type = type;
                [self.navigationController pushViewController:classifySettingVC animated:YES];
            }
            else{
                [weakSelf MakeToast:@"密码错误！" WithTime:2];
            }
        }];
        [self.view addSubview:alertView];
        [alertView show];
        
    } else {
        BSKClassifySettingViewController *classifySettingVC = [[BSKClassifySettingViewController alloc] init];
        classifySettingVC.type = type;
        [self.navigationController pushViewController:classifySettingVC animated:YES];
    }
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"  " handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        BSKNoteType * type = _dataSource[indexPath.row];
        if (type.secretMode) {
            BSKTypePasswdAlertView * alertView = [[BSKTypePasswdAlertView alloc]initWithNoteType:type successCallBack:^(BOOL isSuccess) {
                if(isSuccess){
                    [weakSelf deleteAType:type];
                }
                else{
                    [weakSelf MakeToast:@"密码错误！" WithTime:2];
                }
            }];
            [self.view addSubview:alertView];
            [alertView show];
            
        } else {
            [weakSelf deleteAType:type];
        }
        
    }];
    deleteAction.backgroundColor = [UIColor clearColor];
    return @[deleteAction];
}


@end
